import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件
// @符号代表src目录
// import login from '@/views/login/index.vue'
// 它默认会找这个文件夹里的package.json,index.js,index.vue
// import login from '@/views/login'
// import layout from '@/layout'
// import home from '@/views/home'
// import ask from '@/views/ask'
// import video from '@/views/video'
// import mine from '@/views/mine'
// import edit from '@/views/mine/edit'
// import article from '@/views/article'
// import search from '@/views/search'
// import result from '@/views/search/result'
// import chat from '@/views/mine/chat'

const login = () => import('@/views/login')
const layout = () => import('@/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const video = () => import('@/views/video')
const mine = () => import('@/views/mine')
const edit = () => import('@/views/mine/edit')
const article = () => import('@/views/article')
const search = () => import('@/views/search')
const result = () => import('@/views/search/result')
const chat = () => import('@/views/mine/chat')

Vue.use(VueRouter)
const routes = [
  { path: '/', redirect: '/layout/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'article', path: '/article', component: article },
  { name: 'search', path: '/search', component: search },
  { name: 'chat', path: '/mine/chat', component: chat },
  {
    name: 'result',
    path: '/search/result/:key',
    component: result,
    meta: { needKeep: true }
  },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit,
    meta: { needLogin: true }
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      // 子路由一般不加/，代表拼接父路由来访问
      { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      { name: 'mine', path: 'mine', component: mine, meta: { needLogin: true } }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导入store
import store from '@/store'
import { Toast } from 'vant'
// 全局前置守卫
// 全局：所有路由都会触发
// 前置：进入路由前触发
// to： 去哪的路由信息
// from： 从哪来的路由信息
// next： 是一个函数，调用就代表放行，不调用就不放行
router.beforeEach((to, from, next) => {
  // 去的要登录的页面
  if (to.meta.needLogin) {
    // 有token代表登录了
    if (store.state.tokenObj.token) {
      // 代表登录了
      next()
    } else {
      // 放行到/login的路由，也就是登录页
      // 要把当前原本要去的路径给记录下来，而且还要传给登录页
      // 那也就意味着，现在跳转到登录页的时候还得携带一个参数
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
      Toast.fail('请先登录')
    }
  } else {
    // 去的是不需要登录的页面
    next()
  }
})

// 吞掉路由没跳转的错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch((err) => err)
}

export default router
